import {useRequest} from "ahooks";
import {playlistCatList, subType, playlistCatListDataType} from "@src/services/music.ts";
import {Swiper, SwiperSlide} from "swiper/react";
import type {Swiper as SwiperRef} from 'swiper';
import "./index.scss"
import React, {useEffect, useState} from "react";
import Return2Icon from "@src/assets/return2.svg?react"
import Drawer from "@src/components/Drawer";
import {useNavigate} from "react-router-dom";

type CategoryItem = {
    data: Array<subType>;
    category: number;
    name: string;
};

//
function transformSubData(data: playlistCatListDataType): CategoryItem[] {
    const {sub, categories} = data;

    // 创建一个记录每个 category 的数组
    const result: CategoryItem[] = Object.keys(categories).map((key) => ({
        data: [],
        category: Number(key),
        name: categories[key],
    }));

    // 遍历 sub 数组，将每个 item 放入对应的 category 中
    sub.forEach((item) => {
        const categoryIndex = item.category.toString();
        if (categories[categoryIndex] !== undefined) {
            const index = Object.keys(categories).indexOf(categoryIndex);
            if (index !== -1) {
                result[index].data.push(item);
            }
        }
    });

    return result;
}

interface TagListProps {
    tag: string;
    setTag: React.Dispatch<React.SetStateAction<string>>;
}

export default function TagList({tag, setTag}: TagListProps) {
    const navigate = useNavigate();
    const playlistCatListApi = useRequest(playlistCatList, {manual: true})
    const [isShow, setIsShow] = useState<boolean>(false);
    const [mySwiper, setMySwiper] = useState<SwiperRef>();
    const [drawerData, setDrawerData] = useState<CategoryItem[]>();
    const drawerTagClick = (item: subType) => {
        if (playlistCatListApi.data == undefined) return
        setTag(item.name);
        setIsShow(false)
        const index = playlistCatListApi.data?.sub.indexOf(item) - 2
        mySwiper?.slideTo(index, 500, true)
    }
    useEffect(() => {
        playlistCatListApi.runAsync().then((data) => {
            setDrawerData(transformSubData(data))
        })
    }, [])
    useEffect(() => {
        if (playlistCatListApi.data !== undefined) {
            const index = playlistCatListApi.data?.sub.findIndex(item => item.name === tag)
            mySwiper?.slideTo((index - 2), 500, true)
        }
    }, [mySwiper, playlistCatListApi.data])
    return <>
        <div className="tag-list">
            <div className="tag-swiper centered">
                <Return2Icon className="return-icon" onClick={() => navigate("/home/music")}></Return2Icon>
                <Swiper onSwiper={(swiper) => setMySwiper(swiper)} slidesPerView={5} freeMode={true}>
                    {playlistCatListApi.data?.sub.map((item, index) => {
                        return <SwiperSlide key={item.name} onClick={() => {
                            setTag(item.name)
                            mySwiper?.slideTo(index - 2, 500, true)
                        }}>
                            <div className={"tag centered " + ((item.name == tag) && "active")}>
                                {item.name}
                            </div>
                        </SwiperSlide>
                    })}
                    <SwiperSlide></SwiperSlide>
                </Swiper>
                <Return2Icon className="drawer-show-icon" onClick={() => setIsShow(true)}
                             style={{transform: isShow ? "rotate(-90deg)" : ""}}>
                </Return2Icon>
            </div>
        </div>
        <Drawer position="top" height="45%" isOpen={isShow} setIsOpen={setIsShow}>
            <div className="tag-list-Drawer">
                <ul className="tag-list-Drawer-ul">
                    {drawerData?.map((item) =>
                        <li key={item.category}>
                            <h5>{item.name}</h5>
                            <ul>
                                {item.data.map((item2) =>
                                    <li key={item2.name}
                                        className={"tag centered " + ((item2.name == tag) && "active")}
                                        onClick={() => drawerTagClick(item2)}>{item2.name}
                                    </li>
                                )}
                            </ul>
                        </li>
                    )}
                </ul>
            </div>
        </Drawer>
    </>
}